import pynput.keyboard as ky
import serial
import time
import threading
from maLogger import *

maxtimeout = 10

class VirtualKeyboard(ky.Controller):
    def __init__(self, *args, **kargs):
        self._logger = maGetLogger('keyboard')
        self.port = serial.Serial()
        self.port.baudrate = 115200
        self.__lkey = '' #记录按下的键值
        self.__keypressed_timeout = 0 #用于记录按键是否一直被按下
        self.port.timeout = 3
        self.serial_task_thread = threading.Thread(name='serial', target=self._serial_task_entry)
        ky.Controller.__init__(self, *args, **kargs)

    def begin(self, name, baud = 115200):
        self.port.baudrate = baud
        self.port.port = name
        try:
            if not self.port.is_open:
                self.port.open()
                self._logger.info('open port %s success.'%name)
                self.serial_task_thread.start()
                return True
            else:
                self._logger.info('port %s is already open.'%name)
                return True
        except BaseException as e:
            self._logger.error(e)
            return False
    
    def _serial_task_entry(self):
        while(True):
            if self.port.in_waiting>0:
                msg = bytes.decode(self.port.readline())
                self.port.flush()
                if(len(msg)>0):
                    msg = msg[0]
                    self.__lkey = msg
                    self._logger.debug(msg)
                    #self.__keypressed_timeout = maxtimeout #刷新按键
            time.sleep(0.001)

    def pressKey(self, k):
        #self.__keypressed_timeout = maxtimeout 
        vkd.press(k)
        time.sleep(0.1)
        vkd.release(k)
        self.__lkey = ''
        time.sleep(0.1)
    
    def waitKey(self):
        while(True):
            if(len(self.__lkey)>0):
                self.pressKey(self.__lkey)
            time.sleep(0.001)

if __name__ == '__main__':
    initLogger()
    vkd = VirtualKeyboard()
    vkd.begin('COM17')
    vkd.waitKey()